/*
 * @Description:
 * @Author: fhw
 * @Date: 2022-08-06 13:48:11
 */
import { forwardRef, HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { UserChatRecord } from 'src/chat-record/entities/user-chat-record.entity'
import { socketError, SocketType, throwHttp } from 'src/utlis'
import { Repository, In } from 'typeorm'
import { ChatUserFriend } from '../../chat_user_friends/entities/chat_user_friend.entity'

@Injectable()
export class SocketMessageService {
  constructor(
    @InjectRepository(UserChatRecord)
    private userChatRecordRepository: Repository<UserChatRecord>,
    @InjectRepository(ChatUserFriend)
    private chatUserFriendRepository: Repository<ChatUserFriend>,
  ) { }
  async unreadChatRecord(params): Promise<{ [index: string]: number } | SocketType> {
    try {
      const { userId } = params
      const userFriends = await this.chatUserFriendRepository.find({
        where: { userId: userId },
        select: ['friendsId'],
      })
      const friendIds = userFriends.map((itme) => itme.friendsId)
      const userChatRecord = await this.userChatRecordRepository.find({
        where: {
          userId: In(friendIds),
          isRead: 0,
          to_userId: userId,
        },
      })
      const data = {}
      userChatRecord.forEach((item) => {
        if (!data[item.to_userId]) {
          data[item.to_userId] = 0
        }
        data[item.to_userId]++
      })

      return data
    } catch (error) {
      return socketError(error.message) as SocketType
    }
  }
  /** 获取未读好友记录 */
  async getUnreadFriendsRecord(params) {
    try {
      const { userId } = params
      const userFriendRecord = await this.chatUserFriendRepository.find({
        where: {
          userId: userId,
          isRead: 0,
          del: '1'
        },
      })
      const data = {}
      userFriendRecord.forEach((item) => {
        if (!data[item.friendsId]) {
          data[item.friendsId] = 0
        }
        data[item.friendsId]++
      })
      return data
    } catch (error) {
      return socketError(error.message) as SocketType
    }
  }
  /** 设置好友未读记录 */
  async setFriendsUnreadRecord(ids: number[]) {
    try {
      const { affected } = await this.chatUserFriendRepository
        .createQueryBuilder()
        .update(ChatUserFriend)
        .set({ isRead: 1 })
        .where({ friendsId: In(ids) })
        .execute()
      if (affected) {
        return {
          success: true,
          msg: '更新成功',
        }
      }
    } catch (error) {
      return socketError(error.message) as SocketType
    }
  }
}
